<template>
  <div>
    <dialog-content :dialogOptions="dialogOptions || (new Date().getTime())">
      <template slot="dialog-content_content">
        <form-content ref="roleInfoForm" :formOptions="formOptions" :formSource="formSource" @changeHandle="changeHandle">
        </form-content>
      </template>
      <template slot="dialog-content_footer">
        <el-button v-if="type !== 1 && isAuth('sys:role:save')" type="primary" v-prevent-re-click
         :size="this.size" @click="submitHandle('save')">保 存</el-button>
        <el-button v-if="type === 1 && isAuth('sys:role:update')" type="primary" v-prevent-re-click
         :size="this.size" @click="submitHandle('edit')">修 改</el-button>
        <el-button v-if="type === 1 && isAuth('sys:role:delete')" type="danger" v-prevent-re-click
         :size="this.size" @click="submitHandle('delete')">删 除</el-button>
        <el-button :size="this.size" @click="dialogOptions.show = false">取 消</el-button>
      </template>
    </dialog-content>
  </div>
</template>

<script>
import DialogContent from '@/components/common/dialog-content'
import FormContent from '@/components/common/form-content'
import { getRoleTreeApi, getRoleInfoApi, saveRoleApi, updateRoleApi, deleteRoleApi } from '@/api/role'
export default {
  components: { DialogContent, FormContent },
  props: {
    size: {
      type: String,
      default: 'small'
    },
    nodeId: {
      type: String,
      default: '0'
    }
  },
  data() {
    return {
      dialogOptions: {
        title: '角色信息',
        show: false,
        modal: true,
        width: '350px',
        height: '170px',
        center: true
      },
      formOptions: {
        inline: true,
        labelPosition: 'right',
        labelWidth: '80px',
        labelSuffix: '',
        size: this.size
      },
      formSource: {
        operations: [
          {
            name: '代码',
            key: 'code',
            type: 'text',
            width: '200px',
            length: 20
          },
          {
            name: '名称',
            key: 'name',
            type: 'text',
            width: '200px',
            length: 20
          },
          {
            name: '备注',
            key: 'remark',
            type: 'textarea',
            width: '200px',
            length: 250
          },
          {
            name: '选择上级',
            key: 'roleTree',
            type: 'cascader',
            cascaderProps: { checkStrictly: true },
            width: '150px',
            cascaderOptions: []
          }
        ],
        ruleForm: {},
        rules: {
          code: [{ required: true, message: '代码不能为空', trigger: 'blur' }],
          name: [{ required: true, message: '名称不能为空', trigger: 'blur' }]
        }
      },
      type: 0 // 0添加1查看2修改
    }
  },
  created() {},
  computed: {},
  methods: {
    // type：0默认1查看2修改
    init(id = 0, type = 0) {
      this.type = type
      this.formSource.ruleForm.id = id || 0
      if (id !== undefined && id !== 0 && type !== 0) {
        getRoleInfoApi(id).then(res => {
          let data = res.data
          this.formSource.ruleForm = {
            id: data.id,
            code: data.code,
            name: data.name,
            remark: data.remark,
            parentId: data.parentId
          }
        }).then(() => {
          this.getRoleTree(this.formSource.ruleForm.parentId)
          this.controlInit(this.type)
          this.flushForm(this)
        })
      } else {
        this.formSource.ruleForm = {
          id: '0',
          code: '',
          name: '',
          remark: '',
          parentId: 0
        }
        this.getRoleTree(this.nodeId)
        this.controlInit(this.type)
        this.flushForm(this)
      }
    },
    flushForm(target) {
      if (target.$refs.roleInfoForm === undefined) {
        target.$nextTick(() => {
          target.$refs.roleInfoForm.init()
        })
      } else {
        if (this.type === 0) {
          target.$refs.roleInfoForm.init()
        } else {
          target.$refs.roleInfoForm.update()
          target.$refs.roleInfoForm.clearValidate()
        }
      }
    },
    controlInit(type) {
      if (type === 1) {
        this.dialogOptions.height = '170px'
      } else {
        this.dialogOptions.height = '210px'
      }
      if (type === 0) {
      }
      this.formSource.operations.forEach(item => {
        if (type === 0) {
          item.disabled = false
        } else if (type === 1) {
          item.disabled = true
        } else if (type === 2) {
          if (item.key === 'code') {
            item.disabled = true
          } else {
            item.disabled = false
          }
        }

        if (item.key === 'roleTree') {
          if (type === 1) {
            item.show = false
          } else {
            item.show = true
          }
        }
      })
    },
    getRoleTree(parentId = 0) {
      getRoleTreeApi().then(res => {
        this.formSource.operations.forEach(item => {
          if (item.key === 'roleTree') {
            item.cascaderOptions = this.treeFormat(res.data, 'id', 'name', 'subRoles')
            this.treeForEach(item.cascaderOptions, 'children', item => {
              if (item.value === this.formSource.ruleForm.id) {
                item['disabled'] = true
              }
            })
            this.formSource.ruleForm.roleTree = this.cascaderSuperior(res.data, false, 'subRoles', parentId)
          }
        })
      })
    },
    changeHandle(obj) {
      let _item = obj.backData
      if (_item.key !== 'roleTree') {
        return
      }
      let roleTreeValues = this.formSource.ruleForm[_item.key]
      if (roleTreeValues === undefined || roleTreeValues.length === 0) {
        this.formSource.ruleForm.parentId = 0
        return
      }
      let roleTreeOptions = this.formSource.operations[obj._index].cascaderOptions
      let targetRoleTreeIndex = roleTreeValues.length - 1
      let item = this.treeRetrieval(roleTreeOptions, 'value', roleTreeValues[targetRoleTreeIndex], 'children')
      this.formSource.ruleForm.parentId = item.value
    },
    submitHandle(type) {
      if (type === 'edit') {
        this.type = 2
        this.controlInit(this.type)
        this.flushForm(this)
        return false
      }
      if (!this.$refs.roleInfoForm.submitForm()) return false

      if (this.formSource.ruleForm.id) {
        if (type !== 'delete') {
          updateRoleApi(this.formSource.ruleForm).then(res => {
            this.$message({
              message: '修改成功',
              type: 'success',
              duration: 1500
            })
            this.dialogOptions.show = false
            this.$emit('flush')
          }).catch(() => {
            this.$message({
              message: '修改失败',
              type: 'error',
              duration: 1500
            })
          })
        } else {
          this.$confirm('是否删除下级角色?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            deleteRoleApi(this.formSource.ruleForm.id, true).then(res => {
              this.$message({
                message: '删除成功',
                type: 'success',
                duration: 1500
              })
              this.dialogOptions.show = false
              this.$emit('flush')
            }).catch(() => {
              this.$message({
                message: '删除失败',
                type: 'error',
                duration: 1500
              })
            })
          }).catch(() => {
            deleteRoleApi(this.formSource.ruleForm.id).then(res => {
              this.$message({
                message: '删除成功',
                type: 'success',
                duration: 1500
              })
              this.dialogOptions.show = false
              this.$emit('flush')
            }).catch(() => {
              this.$message({
                message: '删除失败',
                type: 'error',
                duration: 1500
              })
            })
          })
        }
      } else {
        saveRoleApi(this.formSource.ruleForm).then(res => {
          this.$message({
            message: '添加成功',
            type: 'success',
            duration: 1500
          })
          this.dialogOptions.show = false
          this.$emit('flush')
        }).catch(() => {
          this.$message({
            message: '添加失败',
            type: 'error',
            duration: 1500
          })
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
